package service

import (
	"context"
	"fmt"
	"videosS_rpc/basic/config"
	__ "videosS_rpc/basic/proto"
	"videosS_rpc/handler/model"
	"videosS_rpc/pkg"
)

func (s *Server) Register(_ context.Context, in *__.RegisterReq) (*__.RegisterResp, error) {

	count, _ := config.Rdb.Get(config.Ctx, "SendKey"+in.UserName).Result()
	if count != in.SendSms {
		return nil, fmt.Errorf("短信验证码验证失败,请重试")
	}

	user := model.User{
		UserName:     in.UserName,
		Password:     pkg.Md5(in.Password),
		Status:       int(in.Status),
		MemberStatus: int(in.MemberStatus),
	}
	err := user.Register(config.DB)
	if err != nil {
		return nil, err
	}

	return &__.RegisterResp{
		UserId: int64(user.ID),
	}, nil
}

func (s *Server) Login(_ context.Context, in *__.LoginReq) (*__.LoginResp, error) {

	count, _ := config.Rdb.Get(config.Ctx, "SendKey"+in.UserName).Result()
	if count != in.SendSms {
		return nil, fmt.Errorf("短信验证码验证失败,请重试")
	}

	user := model.User{}
	err := user.IsUserName(config.DB, in.UserName)
	if err != nil {
		return nil, err
	}
	return &__.LoginResp{
		UserId: int64(user.ID),
	}, nil
}
